<template>
  <div class="shopWrapper">
    <el-card class="shop-header">
      <div class="shop-head-img">
        <img
          :src="require('@/assets/logo.png')"
          alt="秒杀银行"
          class="img1"
        />
      </div>
      <div class="shop-head-title">
        <div class="shop-head-title-top">
          <span class="span-font"
            >银行秒杀商城欢迎你！
            <span>
              <strong>{{ enterUserName }}</strong>
            </span>
          </span>
        </div>
        <div class="shop-head-title-bottom">
          <p class="left">
            秒杀商城：<span>秒你所想</span> &nbsp; 尽快付款：<span
              >占得先机</span
            >
          </p>
          <p class="right">
            <el-button type="info" size="small" @click="outLogin"
              >退出登录</el-button
            >
          </p>
        </div>
      </div>
    </el-card>
    <div class="shop-body margin-top-10" v-loading="KillbodyLoading">
      <el-tabs
        tab-position="left"
        style="height: 100%"
        class="body-demo-tabs"
        @tab-click="tabOnclickBtn"
        model-value="shoptwoPage"
      >
        <el-tab-pane label="秒杀活动" name="shopOnePage">
          <div class="shop-content" v-loading="loading">
            <el-scrollbar wrap-class="scrollbar-wrapper">
              <el-row class="magin-top-20 el-row-center"
                ><el-pagination
                  :page-size="pageSize"
                  layout="total, prev, pager, next"
                  :total="total"
                  @current-change="handleCurrentChange"
                />
              </el-row>

              <el-card v-for="item in AllActivityArray" :key="item.id">
                <el-descriptions :title="item.activityName" size="small">
                  <template #extra>
                    <el-button
                      type="success"
                      @click="myApplyBtn(item.id)"
                      v-if="item.status == 0"
                      size="small"
                      v-loading="btnloading"
                      >秒杀申请</el-button
                    >
                    <el-tag type="info" effect="dark" v-else>活动结束</el-tag>
                  </template>
                  <el-descriptions-item label="活动开始时间:">{{
                    item.activityStartTime
                  }}</el-descriptions-item>
                  <el-descriptions-item label="活动持续时间:">
                    {{ item.activityLastTime }}
                  </el-descriptions-item>
                  <el-descriptions-item label="活动结束时间:">
                    {{ item.activityEndTime }}
                  </el-descriptions-item>
                  <el-descriptions-item label="详情内容">
                    <el-button
                      type="primary"
                      size="small"
                      @click="getDetailBtn(item)"
                      >活动详情
                    </el-button>
                  </el-descriptions-item>
                  <el-descriptions-item label="活动规则:">
                    {{ item.activityRule }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-card>
            </el-scrollbar>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我的申请" name="shoptwoPage">
          <div
            class="shop-content"
            v-loading="mykillLoading"
            element-loading-text="正在秒杀中..."
          >
            <el-scrollbar>
              <el-card
                v-for="item in AllmyApplyArray"
                :key="item.id"
                class="margin-top-10"
              >
                <el-descriptions :title="item.activityName" size="small">
                  <template #extra>
                    <el-tag v-show="false"> {{ testFun(item) }} </el-tag>
                    <el-tag
                      type="info"
                      effect="dark"
                      v-if="killTimeFun(item) == 0"
                      >活动结束</el-tag
                    >
                    <el-tag effect="dark" v-else-if="killTimeFun(item) == 2"
                      >三分钟内</el-tag
                    >
                    <el-button
                      v-else-if="killTimeFun(item) == 1"
                      type="danger"
                      @click="BankillBtn(item)"
                      size="small"
                      v-loading="btnloading"
                      >正在秒杀...</el-button
                    >
                    <el-tag effect="dark" v-else>等待中</el-tag>
                  </template>
                  <el-descriptions-item label="活动开始时间:">{{
                    item.activityStartTime
                  }}</el-descriptions-item>
                  <el-descriptions-item label="活动持续时间:">
                    {{ item.activityLastTime }}
                  </el-descriptions-item>
                  <el-descriptions-item label="活动结束时间:">
                    {{ item.activityEndTime }}
                  </el-descriptions-item>
                  <el-descriptions-item label="详情内容">
                    <el-button
                      type="primary"
                      size="small"
                      @click="getDetailBtn(item)"
                      >活动详情
                    </el-button>
                  </el-descriptions-item>
                  <el-descriptions-item label="活动规则:">
                    {{ item.activityRule }}
                  </el-descriptions-item>
                  <el-descriptions-item label="倒计时:"
                    ><el-tag>{{
                      item.timeDays +
                      "天" +
                      item.timeHours +
                      "小时" +
                      item.timeMins +
                      "分钟" +
                      item.timeSeds +
                      "秒"
                    }}</el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </el-card>
            </el-scrollbar>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我的订单" name="shopThreePage">
          <div class="shop-content">
            <el-scrollbar>
              <!-- 开始 -->
              <div>
                <el-card>
                  <el-table
                    :data="tableData"
                    style="width: 100%"
                    :header-cell-style="{ 'text-align': 'center' }"
                    :cell-style="{ 'text-align': 'center' }"
                    v-loading="Tabloading"
                  >
                    <el-table-column prop="orderCreateTime" label="生成时间" />
                    <el-table-column prop="orderId" label="订单编号" />
                    <el-table-column prop="price" label="活动商品价格" />

                    <el-table-column
                      prop="orderEditTime"
                      label="订单状态变动时间"
                    />
                    <el-table-column label="支付状态">
                      <template #default="props">
                        <el-button
                          type="danger"
                          effect="dark"
                          v-loading="btnloading"
                          size="small"
                          @click="OrderPayBtn(props.row)"
                          v-if="props.row.orderStatus == 0"
                        >
                          <el-icon> <pointer /></el-icon>立即支付</el-button
                        >
                        <el-tag
                          effect="dark"
                          type="success"
                          v-else-if="props.row.orderStatus == 1"
                          >支付成功</el-tag
                        >
                        <el-tag
                          effect="dark"
                          type="warning"
                          v-else-if="props.row.orderStatus == 3"
                          >排队中...</el-tag
                        >
                        <el-tag type="info" effect="dark" v-else
                          >订单关闭</el-tag
                        >
                      </template>
                    </el-table-column>
                    <el-table-column label="活动详情">
                      <template #default="props">
                        <el-button
                          size="small"
                          round
                          type="primary"
                          @click="getReDetailBtn(props.row)"
                        >
                          <el-icon><goods /></el-icon>活动详情</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-row class="el-row-center">
                    <el-pagination
                      :page-size="mypageSize"
                      layout="total, prev, pager, next"
                      :total="mytotal"
                      @current-change="MyhandleCurrentChange"
                    ></el-pagination>
                  </el-row>
                </el-card>

                <!-- 活动内容弹出框 -->
              </div>
              <!-- 结束 -->
            </el-scrollbar>
          </div></el-tab-pane
        >
        <el-tab-pane name="" label="秒杀记录">
          <div class="shop-content">
            <el-scrollbar>
              <el-card>
                <el-table
                  :header-cell-style="{ 'text-align': 'center' }"
                  :cell-style="{ 'text-align': 'center' }"
                  v-loading="Tabloading"
                  :data="mySuccesstableData"
                >
                  <el-table-column
                    property="createTime"
                    label="秒杀时间"
                  ></el-table-column>
                  <!-- <el-table-column
          property="userName"
          label="秒杀用户"
        ></el-table-column> -->
                  <el-table-column
                    property="activityName"
                    label="活动名称"
                  ></el-table-column>
                  <el-table-column label="状态" prop="status"></el-table-column>
                  <el-table-column label="活动详情">
                    <template #default="props">
                      <el-button
                        size="small"
                        round
                        type="primary"
                        @click="getReDetailBtn(props.row)"
                      >
                        <el-icon><goods /></el-icon>活动详情</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
                <el-row class="el-row-center">
                  <el-pagination
                    :page-size="myKillpageSize"
                    layout="total, prev, pager, next"
                    :total="myKilltotal"
                    @current-change="MyKillhandleCurrentChange"
                  >
                  </el-pagination
                ></el-row>
              </el-card>
            </el-scrollbar>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 活动内容弹出框 -->
    <el-dialog v-model="activityContentDialogVisible" title="活动内容">
      <el-table
        :data="Activitycontent"
        :show-header="false"
        style="width: 100%"
      >
        <el-table-column prop="label"></el-table-column>
        <el-table-column>
          <template #default="prop">
            <span> {{ detailContentData[prop.row.value] }} </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 订单 -->
    <el-dialog v-model="activityPayDialogVisible" title="活动内容">
      <el-row> 订单号：{{ orderId }} </el-row>
      <el-row> 截止时间：{{ deadTime }} </el-row>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="delayPayBtn">等下支付</el-button>
          <el-button @click="payItBtn" v-bind="btnloading" type="primary"
            >立即支付</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="readTheInfoDialogVisible" title="秒杀注意事项">
      <p>
        <strong
          >该页面刷新机制是点击导航菜单刷新，随时看《我的订单》页面</strong
        >
      </p>
      <p class="font-size:50px">
        注意秒杀时间很短，尽快支付，<strong>
          只要有了支付订单弹出框，就产生了订单</strong
        >, <strong>支付后等待返回结果，不要做其他操作，不然可能失败</strong>
      </p>

      <p><strong> 登录时间有限，服务器报错，注意退出重新登录</strong></p>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs } from "vue";
import {
  successMessage,
  errorMessage,
  warnMessage,
  infoMessage,
} from "@/utils/messageTips";
import { storageSession, storageLocal } from "@/storage/index";
import { useRouter } from "vue-router";
import {
  ApiGetShopsList,
  ApiGetShopActivityDetail,
  ApiGetShopBuyInfo,
  ApiGetShopPay,
  ApiGetShopMyApplyList,
  ApiGetShopKillPath,
  ApiGetShopSuccessOrder,
  ApiGetShopApplyActivity,
  ApiGetShopGoodByUser,
  ApiGetShopMyOrder,
  ApiGetMyKillList,
} from "@/api/index";
import dayjs from "dayjs";
import { left } from "@popperjs/core";
export default defineComponent({
  name: "Shop",
  setup() {
    let pageInfo = reactive<IGPageInfo>({
      pageNum: 1,
      total: 2,
      pages: 2,
      pageSize: 15,
    });
    let Tabloading = ref<boolean>(false);
    let mykillLoading = ref<boolean>(false);
    let loading = ref<boolean>(true);
    let btnloading = ref<boolean>(false);
    let KillbodyLoading = ref<boolean>(false);
    const enterUserName = storageSession.getItem("username");
    let tabsName = ref<string>("");
    let pageShopContent = ref<number>(1);
    const Activitycontent = [
      { label: "活动名称", value: "activityName" },
      { label: "活动规则", value: "activityRule" },
      { label: "活动详情", value: "activityDetail" },
      { label: "活动结束时间", value: "activityEndTime" },
      { label: "当前产品名字", value: "goodName" },
      { label: "产品详情", value: "goodDetail" },
      { label: "产品价格", value: "goodPrice" },
      { label: "产品使用手册介绍", value: "manual" },
      { label: "客户须知", value: "notice" },
      { label: "产品限购量", value: "limitNum" },
    ];

    // 所有对话视窗
    const AllDialogVisible = reactive<Record<string, boolean>>({
      activityContentDialogVisible: false,
      activityPayDialogVisible: false,
      readTheInfoDialogVisible: false,
    });

    let AllActivityArray = ref<Array<any>>();
    let detailContentData = ref({});
    let AllmyApplyArray = ref<Array<any>>();
    const ActivityDetailandGood = async (activityRes: any, goodId: number) => {
      const { data: goodres } = (await ApiGetShopGoodByUser(goodId)) as Record<
        string,
        any
      >;
      detailContentData.value = { ...activityRes, ...goodres };
      loading.value = false;
      Tabloading.value = false;
      AllDialogVisible.activityContentDialogVisible = true;
    };
    // tab切换
    const tabOnclickBtn = (tab) => {
      if (tab.index == 0) {
        getAllActivity();
      } else if (tab.index == 1) {
        getMyApplyList();
      } else if (tab.index == 2) {
        getRecords();
      } else {
        mySuccessList();
      }
    };

    // 获取所有活动信息
    const getAllActivity = async () => {
      loading.value = true;
      try {
        const { data: res } = (await ApiGetShopsList(
          pageInfo.pageNum
        )) as Record<string, any>;
        AllActivityArray.value = res.list;
        pageInfo.total = res.total;
        pageInfo.pageSize = res.pageSize;
      } catch (err) {
        errorMessage(
          "服务器或者网络问题，浏览器刷新一下，也可能登录时间过期！！！，请重新登录"
        );
        outLogin();
      }
      loading.value = false;
      btnloading.value = false;
      if (AllActivityArray.value?.length == 0) {
        warnMessage("现在还没有发布任何活动");
      }
    };
    // 改变页码
    const handleCurrentChange = (val: number) => {
      pageInfo.pageNum = val;
      getAllActivity();
    };
    // 活动详情
    const getDetailBtn = async (info) => {
      loading.value = true;
      const { data: res } = (await ApiGetShopActivityDetail(info.id)) as Record<
        string,
        any
      >;
      const goodId = res.goodId;
      const tempCopy = {};
      Object.assign(tempCopy, info);
      ActivityDetailandGood(tempCopy, goodId);
    };
    // 申请判断
    const myApplyBtn = async (id: number) => {
      btnloading.value = true;

      const res = (await ApiGetShopApplyActivity(id)) as Record<string, any>;

      if (res.code == 1) {
        successMessage(res.message);
      } else {
        errorMessage(res.message);
      }
      btnloading.value = false;
    };

    // 获取我的申请列表
    const getMyApplyList = async () => {
      try {
        KillbodyLoading.value = true;
        const { data: res } = (await ApiGetShopMyApplyList()) as Record<
          string,
          any
        >;
        AllmyApplyArray.value = res.list.map((item) => {
          return {
            ...item,
            timeDays: 0,
            timeHours: 0,
            timeMins: 0,
            timeSeds: 0,
          };
        });

        if (AllmyApplyArray.value?.length == 0) {
          warnMessage("当前申请记录已为空！！");
        }
      } catch (err) {
        errorMessage("服务器或者网络问题，浏览器刷新一下，或者重新登录一下");
        outLogin();
      }

      btnloading.value = false;
      KillbodyLoading.value = false;
      mykillLoading.value = false;
    };
    // 秒杀刷新
    const killRefreshBtn = async () => {
      btnloading.value = true;
      KillbodyLoading.value = true;
      await getMyApplyList();
    };
    // 时间延缓
    const sleepIt = async (time) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("调用");
        }, time);
      });
    };
    // 活动刷新
    const activityRefreshBtn = async () => {
      btnloading.value = true;
      await getAllActivity();
    };
    // 时间函数
    function DifferentTimeFun(activityStartTime) {
      let nowTime = new Date().getTime() / 1000;
      let killTime = new Date(activityStartTime).getTime() / 1000;
      return Math.round(killTime - nowTime);
    }
    // 时间逻辑
    const killTimeFun = (item) => {
      let endTime = new Date(item.activityEndTime).getTime() / 1000;
      let nowTime = new Date().getTime() / 1000;
      if (endTime - nowTime < 0) {
        return 0; //结束了
      }
      let differenceTime = DifferentTimeFun(item.activityStartTime);
      if (differenceTime < 0) {
        return 1; //正在抢
      }
      if (differenceTime <= 181) {
        return 2; //特殊时间
      } else {
        return 3; //等待
      }
    };
    // 秒杀
    let payOrderForm = reactive<{
      orderId: number;
      deadTime: string;
      theActivityId: number;
    }>({
      orderId: 0,
      deadTime: "",
      theActivityId: 0,
    });

    // 秒杀开始流程
    const BankillBtn = async (info) => {
      mykillLoading.value = true;
      payOrderForm.theActivityId = info.id;
      try {
        const res = (await ApiGetShopKillPath(info.id)) as Record<string, any>;

        if (res.code == 1) {
          const pathres = (await ApiGetShopBuyInfo(
            res.data,
            info.id
          )) as Record<string, any>;
          console.log(pathres);
          if (pathres.code == 1) {
            payOrderForm.orderId = pathres.data.orderId;
            payOrderForm.deadTime = dayjs(pathres.data.deadTime).format(
              "YYYY-MM-DD HH:mm:ss"
            );
            AllDialogVisible.activityPayDialogVisible = true;
          } else {
            errorMessage(pathres.message);
          }
        } else {
          errorMessage(res.message);
        }
      } catch (err) {
        errorMessage("后台或者网络服务器设置出现了问题");
      }
      mykillLoading.value = false;
    };
    // 表格付款
    const OrderPayBtn = async (info) => {
      btnloading.value = true;
      Tabloading.value = true;
      const res = (await ApiGetShopPay(
        info.orderId,
        info.activityId
      )) as Record<string, any>;
      if (res.code == 1) {
        successMessage(res.message);
      } else if (res.code == 40008) {
        let orderPay = (await ApiGetShopSuccessOrder(
          payOrderForm.theActivityId
        )) as Record<string, any>;
        while (orderPay.code == 40008) {
          orderPay = (await ApiGetShopSuccessOrder(
            payOrderForm.theActivityId
          )) as Record<string, any>;
          console.log(orderPay.code);
        }
        if (orderPay.code == 1) {
          successMessage(orderPay.message);
        } else {
          errorMessage(orderPay.message);
        }
      } else {
        warnMessage(res.message);
      }
      getRecords();
      btnloading.value = false;
    };
    const delayPayBtn = () => {
      btnloading.value = true;
      getMyApplyList();
      AllDialogVisible.activityPayDialogVisible = false;
    };
    // 对话框付款
    const payItBtn = async () => {
      btnloading.value = true;
      AllDialogVisible.activityPayDialogVisible = false;
      mykillLoading.value = true;
      const res = (await ApiGetShopPay(
        payOrderForm.orderId,
        payOrderForm.theActivityId
      )) as Record<string, any>;
      if (res.code == 40008) {
        warnMessage("正在秒杀排队中.......");
        let orderPay = (await ApiGetShopSuccessOrder(
          payOrderForm.theActivityId
        )) as Record<string, any>;
        console.log(orderPay);
        while (orderPay.code == 40008) {
          orderPay = (await ApiGetShopSuccessOrder(
            payOrderForm.theActivityId
          )) as Record<string, any>;
          console.log(orderPay.code);
        }
        if (orderPay.code == 1) {
          successMessage(orderPay.message);
        } else {
          warnMessage(orderPay.message);
        }
      } else if (res.code == 1) {
        successMessage(res.message);
      } else {
        warnMessage(res.message);
      }
      getMyApplyList();
      mykillLoading.value = false;

      AllDialogVisible.activityPayDialogVisible = false;
    };

    // 我的订单记录
    let MypageInfo = reactive({
      mypageNum: 1,
      mytotal: 2,
      mypages: 2,
      mypageSize: 15,
    });
    let tableData = ref([]);
    const getRecords = async () => {
      Tabloading.value = true;
      const { data: res } = (await ApiGetShopMyOrder(
        MypageInfo.mypageNum
      )) as Record<string, any>;
      tableData.value = res.list;
      MypageInfo.mytotal = res.total;
      MypageInfo.mypages = res.pages;
      MypageInfo.mypageSize = res.pageSize;

      if (tableData.value.length == 0) {
        warnMessage("还没有您的支付订单信息呢！");
      }
      btnloading.value = false;
      Tabloading.value = false;
    };
    const MyhandleCurrentChange = (val: number) => {
      pageInfo.pageNum = val;
      getRecords();
    };
    const getReDetailBtn = async (info) => {
      Tabloading.value = true;
      let activityId = info.activityId;

      const { data: res } = (await ApiGetShopActivityDetail(
        activityId
      )) as Record<string, any>;
      const goodId = res.goodId;
      const tempCopy = {};
      Object.assign(tempCopy, res);

      ActivityDetailandGood(tempCopy, goodId);
    };
    const RecordRefreshBtn = async () => {
      btnloading.value = true;
      getRecords();
    };
    let MykillPage = reactive({
      myKillNum: 1,
      myKilltotal: 2,
      myKillpages: 2,
      myKillpageSize: 15,
    });
    let mySuccesstableData = ref([]);
    //  我的成功秒杀订单
    const mySuccessList = async () => {
      Tabloading.value = true;
      const { data: res } = (await ApiGetMyKillList(
        MykillPage.myKillNum
      )) as Record<string, any>;
      mySuccesstableData.value = res.list;
      MykillPage.myKillpageSize = res.pageSize;
      MykillPage.myKilltotal = res.total;
      Tabloading.value = false;
      if (mySuccesstableData.value.length == 0) {
        warnMessage("还没有您的秒杀记录订单呢");
      }
    };

    const MyKillhandleCurrentChange = (val: number) => {
      MykillPage.myKillNum = val;
      mySuccessList();
    };
    // 倒计时
    const testFun = (info) => {
      let timer = setInterval(() => {
        let nowTime = new Date();
        let startTime = new Date(info.activityStartTime);
        let leftTime = startTime.getTime() - nowTime.getTime();
        if (leftTime > 0) {
          info.timeDays =
            Math.floor(leftTime / (1000 * 60 * 60 * 24)) < 10
              ? "0" + Math.floor(leftTime / (1000 * 60 * 60 * 24))
              : Math.floor(leftTime / (1000 * 60 * 60 * 24));
          info.timeHours =
            Math.floor(leftTime / (1000 * 60 * 60)) < 10
              ? "0" + Math.floor(leftTime / (1000 * 60 * 60))
              : Math.floor(leftTime / (1000 * 60 * 60));
          info.timeMins =
            Math.floor((leftTime / (1000 * 60)) % 60) < 10
              ? "0" + Math.floor((leftTime / (1000 * 60)) % 60)
              : Math.floor((leftTime / (1000 * 60)) % 60);
          info.timeSeds =
            Math.floor((leftTime / 1000) % 60) < 10
              ? "0" + Math.floor((leftTime / 1000) % 60)
              : Math.floor((leftTime / 1000) % 60);
        } else {
          info.timeDays = "00";
          info.timeHours = "00";
          info.timeMins = "00";
          info.timeSeds = "00";
          clearInterval(timer);
        }
      }, 1000);
    };

    const router = useRouter();
    const outLogin = () => {
      sessionStorage.clear();
      router.push("/login");
    };
    onMounted(async () => {
      successMessage("欢迎来到秒杀页面");

      await getMyApplyList(),
        (AllDialogVisible.readTheInfoDialogVisible = true);
    });
    return {
      enterUserName,
      tabsName,
      pageShopContent,
      outLogin,
      AllActivityArray,
      getDetailBtn,
      Activitycontent,
      ...toRefs(AllDialogVisible),
      ...toRefs(payOrderForm),
      loading,
      detailContentData,
      myApplyBtn,
      btnloading,
      AllmyApplyArray,
      BankillBtn,
      killTimeFun,
      killRefreshBtn,
      KillbodyLoading,
      activityRefreshBtn,
      payItBtn,
      handleCurrentChange,
      ...toRefs(pageInfo),
      mykillLoading,
      ...toRefs(MypageInfo),
      MyhandleCurrentChange,
      tableData,
      getReDetailBtn,
      Tabloading,
      RecordRefreshBtn,
      tabOnclickBtn,
      OrderPayBtn,
      delayPayBtn,
      MyKillhandleCurrentChange,
      ...toRefs(MykillPage),
      mySuccesstableData,
      testFun,
    };
  },
});
</script>
